package com.jason.platform.supervision.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewGroup;
import com.hzlj.supervision.changsha.R;
import com.jason.platform.supervision.base.Constant;
import com.jason.platform.supervision.beans.Category;
import com.jason.platform.supervision.beans.LocateBean;
import com.jason.platform.supervision.fragment.BaseFragment;
import com.jason.platform.supervision.fragment.MonitorChildFragment;
import com.jason.platform.supervision.task.QueryLocateListTask;
import com.jason.platform.supervision.task.QueryRealTimeLocateTask;
import com.jason.platform.supervision.task.Task;
import com.jason.platform.supervision.task.TaskListener;
import com.jason.platform.supervision.utils.SharedPreferencesUtils;
import com.jason.platform.supervision.widght.*;
import org.kymjs.aframe.http.KJFileParams;

import java.util.ArrayList;

/**
 * @ClassName: MonitorActivity
 * @Description: 在线监控
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2015-7-25 09:45:08
 */
public class MonitorActivity extends BaseActivity implements TaskListener{

    private static final String TAG = MonitorActivity.class.getSimpleName();

    private TitleBar mTitleBar;
    private MyHandler<MonitorActivity> mHandler;

    public static boolean isLoading = false;

    //导航栏
    private NavTabBar mNavTabBar;
    private TransformViewPager mViewPager;
    private ArrayList<Category> mNavTabCategorys = new ArrayList<Category>();
    private ArrayList<BaseFragment> mFragments = new ArrayList<BaseFragment>();

    /**
     * 上次页面显示位置
     */
    private int mLastPageIndex = 0;
    private int mCurIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_monitor);
        super.onCreate(savedInstanceState);
        mHandler = new MyHandler<MonitorActivity>(this);
        mTitleBar = (TitleBar) findViewById(R.id.title_bar);
        mTitleBar.bindActivity(this);
    }

    @Override
    protected void initWidget() {
        super.initWidget();
        mNavTabBar = (NavTabBar) findViewById(R.id.monitor_navtab);
        mViewPager = (TransformViewPager) findViewById(R.id.monitor_viewpager);
//        mNavTabCategorys.add(new Category("0", "越界人员"));
        mNavTabCategorys.add(new Category("2", "越界人员"));
        mNavTabCategorys.add(new Category("-2", "定位失败"));
//        mNavTabCategorys.add(new Category("-3", "人机分离"));
//        mNavTabCategorys.add(new Category("-4", "腕带拆卸"));
//        mNavTabCategorys.add(new Category("-5", "低电报警"));
        initFragments();
    }

    @Override
    protected void initLoadingDialog() {
        super.initLoadingDialog();
        mLoadingDialog = new LoadingDialog(this);
        mLoadingDialog.setIsOut(false);
        mLoadingDialog.setMessage("加载中");
    }

    private void initFragments(){
        if (mFragments == null)
            mFragments = new ArrayList<BaseFragment>();

        for (int i = 0; i < mNavTabCategorys.size(); i++) {
            Category category = mNavTabCategorys.get(i);
            mNavTabBar.addNavChildText(category.categoryName, R.drawable.component_navtab_divider1);
            mNavTabBar.totalLength = mNavTabBar.totalLength + category.categoryName.length();
            BaseFragment fragment = new MonitorChildFragment();
            fragment.setTag(mNavTabCategorys.get(i));
            fragment.setArg1(i);
            fragment.setArg2(i);
            mFragments.add(fragment);
        }

        mNavTabBar.setOnNavTabSelectedListener(new NavTabBar.OnNavTabBarSelectedListener() {
            public void onTabSelected(int position) {
                mViewPager.setCurrentItem(position);
            }
        });

        if (mFragments.size() > 0) {
            mViewPager.setOffscreenPageLimit(mFragments.size());
            mViewPager.setAdapter(new SecondPagerAdapter(getSupportFragmentManager()));
        }
        mViewPager.setOnPageChangeListener(new TransformViewPager.OnPageChangeListener() {
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {
            }

            public void onPageScrollStateChanged(int state) {
                Log.i(TAG, "scrollState:" + state);
                if (state == ViewPager.SCROLL_STATE_IDLE) {
                    int curItem = mViewPager.getCurrentItem();
                    mCurIndex = curItem;
                    BaseFragment fragment = (BaseFragment) mFragments.get(mViewPager.getCurrentItem());
                    if (fragment.getNetInitState() == BaseFragment.NetState.INIT_SUCCESS) {
                        fragment.onFrameResume();
                    } else {
                        fragment.onClick(mViewPager.getChildAt(mCurIndex));
                    }

                    Category category = mNavTabCategorys.get(mCurIndex);
                    if (curItem != mLastPageIndex) {
                        BaseFragment preFragment = (BaseFragment) mFragments.get(mLastPageIndex);
                        if (fragment.getNetInitState() == BaseFragment.NetState.INIT_SUCCESS)
                            preFragment.onFrameStop();
                    }
                    mLastPageIndex = curItem;
                }
            }

            public void onPageSelected(int position) {
                mNavTabBar.setSelected(position, false);
                BaseFragment fragment = (BaseFragment) mFragments.get(position);
                if (fragment.getNetInitState() == BaseFragment.NetState.INIT_SUCCESS) {
                    fragment.onFrameResume();
                }
            }
        });


        final DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int size = 15;
        final int width = displayMetrics.widthPixels - size;
        //矫正位置
        new Handler() {
            public void handleMessage(Message msg) {
                mNavTabBar.finishAdd(width, R.drawable.transparent);
            }
        }.sendEmptyMessageDelayed(0, 200L);
    }

    class SecondPagerAdapter extends FragmentPagerAdapter {

        public SecondPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }

        @Override
        public void setPrimaryItem(ViewGroup container, int position,
                                   Object object) {
            super.setPrimaryItem(container, position, object);
            BaseFragment fragment = (BaseFragment) mFragments.get(position);
            if (fragment.getNetInitState() == BaseFragment.NetState.INIT_FIRST) {
                fragment.setNetInitState(BaseFragment.NetState.INITING);
                Category category = mNavTabCategorys.get(position);

                Log.i(TAG,"setPrimaryItem ********* position:" + position);
                Log.i(TAG,"setPrimaryItem ********* " + category.toString());
                QueryLocateListTask task = new QueryLocateListTask(MonitorActivity.this);
                task.type = Constant.Locate.GET_LOCATE_LIST;
                task.mParams.put("currentIndex", "1");
                task.mParams.put("organId", SharedPreferencesUtils.getOrganId(MonitorActivity.this).toString());
//                task.mParams.put("organId", "1");
                task.mParams.put("state", category.categoryID);
                task.arg2 = position;
                task.mIsStart = true;
                task.execute();
            } else {
                fragment.onFrameResume();
            }
        }

    }

    @Override
    void handleMessage(BaseActivity activity, Message msg) {
        Task task = (Task) msg.obj;
        if (task.type == Constant.Locate.GET_LOCATE_LIST ||
                task.type == Constant.Locate.GET_REAL_TIME_LOCATE) {
            Log.i(TAG,"handleMessage...position:" + mCurIndex);
            BaseFragment fragment = (BaseFragment) mFragments.get(task.arg2);
            fragment.onDataCallback(task);
        }
    }

    @Override
    public void onTaskResult(Task task) {
        Message msg = new Message();
        msg.obj = task;
        mHandler.sendMessage(msg);
    }

    public Task getLocateListTask(int type, KJFileParams mParams){
        QueryLocateListTask task = new QueryLocateListTask(MonitorActivity.this);
        task.type = type;
        task.mParams = mParams;
        return task;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    public void getLocate(LocateBean bean){
        //实时定位
        mLoadingDialog.show();
        QueryRealTimeLocateTask task = new QueryRealTimeLocateTask(MonitorActivity.this);
        task.type = Constant.Locate.GET_REAL_TIME_LOCATE;
        task.mParams.put("rymcId", bean.getElectronicsId());
        task.execute();
    }

    public void dismissLoading(){
        if (mLoadingDialog != null){
            mLoadingDialog.dismiss();
        }
    }
}
